<template>
  <div class="historyDataWrap">
    <NavBar
      :title="'历史数据'"
      :text="'返回'"
      :cityName="city"
      :SeveralMenus="'1'"
      @clicksPopul="clicksPopul"
      :areaName="areaName"
    ></NavBar>

    <div id="mapHistory" style="width: 100%; height: 100%"></div>
    <van-collapse class="listbiao" v-model="activeNames">
      <van-collapse-item title="当前市的所有站点数据" name="1">
        <div class="hights">
          <!-- <div class="topTitle">{{ stations }}</div> -->

          <div class="staDistime">
            <span
              style="
                z-index: 9;
                position: absolute;
                left: 10px;
                top: -3px;
                font-size: 13px;
                font-weight: 550;
              "
            >
              选择时间</span
            >
            <img
              style="
                z-index: 9;
                width: 15px;
                height: 15px;
                position: absolute;
                left: 80px;
                top: -3px;
              "
              src="../assets/On-sitedisaster/rili.png"
              alt=""
            />

            <div class="suntime">
              <span @click="selectTimeMet('start')">{{
                endTime | filterTime
              }}</span>
            </div>
          </div>

          <div class="box">
            <!-- class="tdList" -->
            <div class="tdList">
              <div style="width: 60px">
                <div class="tdListsun">站点名</div>
                <div class="tdListsunactive select" @click="Clickisshow">
                  {{ zhantext }}
                </div>
                <div class="selectsun" v-if="isshow">
                  <div
                    :class="active == index ? 'tdListsunactive' : 'tdListsun'"
                    v-for="(item, index) in list"
                    :key="index"
                    @click="clickCity(item, index)"
                  >
                    {{ item.name }}
                  </div>
                </div>
              </div>
              <div style="margin-left: 20px">
                <div class="tdListsun">时间</div>
                <div
                  class="tdListsun"
                  v-for="(item, index) in clickList"
                  :key="index"
                >
                  {{ item.skzdzsTime }}
                </div>
              </div>
              <div>
                <div class="tdListsun">气温</div>
                <div
                  class="tdListsun"
                  v-for="(item, index) in clickList"
                  :key="index"
                >
                  {{ item.skzdzsTem > 999 ? "——" : item.skzdzsTem }}
                </div>
              </div>
              <div>
                <div class="tdListsun" style="width: 100px">10分钟平均风速</div>
                <div
                  class="tdListsun"
                  v-for="(item, index) in clickList"
                  :key="index"
                  style="text-align: center"
                >
                  {{
                    item.skzdzsWindavg10mi > 999 ? "——" : item.skzdzsWindavg10mi
                  }}
                </div>
              </div>
              <div>
                <div class="tdListsun">极大风速</div>
                <div
                  class="tdListsun"
                  v-for="(item, index) in clickList"
                  :key="index"
                >
                  {{ item.skzdzsWindsmax > 999 ? "——" : item.skzdzsWindsmax }}
                </div>
              </div>
              <div>
                <div class="tdListsun">湿度</div>
                <div
                  class="tdListsun"
                  v-for="(item, index) in clickList"
                  :key="index"
                >
                  {{ item.skzdzsRhu > 999 ? "——" : item.skzdzsRhu }}
                </div>
              </div>
              <div>
                <div class="tdListsun">降水</div>
                <div
                  class="tdListsun"
                  v-for="(item, index) in clickList"
                  :key="index"
                >
                  {{ item.skzdzsPre24 > 999 ? "——" : item.skzdzsPre24 }}
                </div>
              </div>

              <div>
                <div class="tdListsun">气压</div>
                <div
                  class="tdListsun"
                  v-for="(item, index) in clickList"
                  :key="index"
                >
                  {{ item.skzdzsPrs > 999 ? "——" : item.skzdzsPrs }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </van-collapse-item>
    </van-collapse>

    <comCity
      v-if="showComArea"
      @closeEmit="showComArea = false"
      @confirmEmit="confirmEmitAreaMet"
      :arr="arr"
    ></comCity>
    <!--时间选择器-->
    <van-popup
      v-model="selectTime"
      get-container="body"
      position="bottom"
      :style="{ width: '100%', height: '40%' }"
    >
      <van-datetime-picker
        v-model="currentDate"
        @cancel="selectTime = false"
        @confirm="confirmTime"
        type="date"
        title="选择年月日"
        :max-date="maxDate"
      />
    </van-popup>
  </div>
</template>
<script type="text/javascript">
import detail from "@/components/historyData/detail.vue";
import comArea from "@/components/common/area.vue";
import comCity from "@/components/common/city.vue";
import meteoroLiveDataApi from "@/service/liveData.js";

import meteoroHistoryApi from "@/service/historyData.js";
import Vue from "vue";
import { Pagination, Collapse, CollapseItem } from "vant";
import { getItem, setItem } from "../util/storage.js";
import map from "@/util/map.js";
Vue.use(Pagination);
Vue.use(Collapse);
Vue.use(CollapseItem);
export default {
  data() {
    return {
      showPopup: false,
      selectTime: false,
      title: "",
      active: 0,
      clickList: [],
      showDetail: false,
      showComArea: false,
      city: "",
      cnty: "",
      activeNames: ["1"],
      isshow: false,
      maxDate: new Date(),
      map: null,
      clearStation: [],
      startTime: "2023-01-01",
      endTime: "",
      Markers: [],
      currentDate: new Date(),
      guojialist: [],
      stations: "当前市的所有站点数据",
      popupInfoWindow: null,
      stationList: [],
      list: [],
      zhantext: "",
      isfn: false,
      totalPage: 1, // 统共页数，默认为1
      currentPage: 1, //当前页数 ，默认为1
      pageSize: 23, // 每页显示数量
      currentPageData: [], //当前页显示内容
      stationsName: "",
      location: [],
      arr: [],
      location1: [],
      areaName:''
    };
  },
  mounted() {
    //设置title

    map.init().then((res) => {
      this.location = getItem("location");
      this.startTime = this.$util.getBeforeDay("-1", "ymd");
      this.endTime = this.$util.getTime("", "ymd");
      this.title = this.location[2].name;

      //设置
      this.city = this.location[1].name;
      this.arr = [this.city];
      this.cnty = this.location[2].name;
      var _this = this;
      _this.location1 = [
        _this.$store.getters.cityLongAndLati[0],

        _this.$store.getters.cityLongAndLati[1],
      ];

      _this.initMap([_this.location1[0], _this.location1[1]]);
    });
  },
  destroyed: function () {
    this.map.remove();
    // 离开页面生命周期函数
    // this.websocketclose()
  },
  watch: {},
  components: {
    detail,
    comArea,
    comCity,
  },
  methods: {
    onChange(event) {
      this.setData({
        activeNames: event.detail,
      });
    },
    initMap(location) {
      var _this = this;
      _this.map = new SGMap.Map({
        // 地图绑定的DOM元素ID
        container: "mapHistory",
        // 地图样式
        style: "aegis://styles/aegis/Streets-v2",
        // 默认缩放层级
        zoom: 7,
        // 地图中心点
        center: location,
        // 地图默认字体
        localIdeographFontFamily: "Microsoft YoHei",
      });
      _this.map.on("load", function (e) {
        _this.$util.initLayershi("", _this.map);
        _this.$util.searchshi(_this.city, _this.map);

        _this.getlist("load");
        var center = _this.map.getCenter();
        var newCenter = new SGMap.LngLat(center.lng, center.lat - 0.5); // 假设向上移动0.01的纬度
        _this.map.panTo(newCenter);
      });
    },
    Clickisshow() {
      this.isshow = !this.isshow;
    },
    clickCity(item, index) {
      this.zhantext = item.name;
      this.active = index;
      this.stationsName = item.name;
      this.isfn = true;

      var time = this.$util.getTime(this.currentDate, "ymd");

      this.clearStation.forEach((it) => {
        if (it == item.acitons) {
          this.map.setLayoutProperty(
            item.acitons,
            "icon-image",
            "pulsing-dot2"
          );
        } else {
          this.map.setLayoutProperty(it, "icon-image", "pulsing-dot1");
        }
        this.map.setCenter([item.lon, item.lat]);
        this.map.setZoom(10);

        this.map.panBy([0, 100]);
      });

      var params = {
        city: this.city,
        time: time,
        name: item.name,
      };
      this.dianFN(params);
    },
    dianFN(params) {
      this.clickList = [];
      meteoroHistoryApi
        .clickStiton(params)
        .then((res) => {
          this.clickList = res;
        })
        .catch((error) => {
          console.log(error);
        });
    },
    //列表
    getlist(load) {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        duration: 0,
      });
      var time = this.$util.getTime(this.currentDate, "ymd");
      var params = {
        // city:this.city
        // time: this.$util.getTime(day,'ymd')
        city: this.city,
        time: time,
        // type: '自动站',
      };
      this.list = [];
      this.guojialist = [];
      meteoroHistoryApi
        .StationList(params)
        .then((res) => {
          var arr = [];
          res.forEach((it) => {
            for (let key in it) {
              it[key].name = key;
              arr.push(it[key]);
            }
          });
          for (let i = 0; i < arr.length; i++) {
            arr[i].acitons = `gjz-${i}`;
          }
          this.guojialist = arr;

          this.list = arr;

          if (load == "load") {
            this.zhantext = arr[0].name;

            var time = this.$util.getTime(this.currentDate, "ymd");
            var params = {
              city: this.city,
              time: time,
              name: arr[0].name,
            };

            this.dianFN(params);
          }
          this.guojiazhandian();

          this.$toast.clear();
        })
        .catch((error) => {});
    },

    // 设置当前页面数据，对数组操作的截取规则为[0~10],[10~20]...,
    setCurrentPageData(val) {
      let begin = (this.currentPage - 1) * this.pageSize;
      let end = this.currentPage * this.pageSize;
      this.currentPageData = this.stationList.slice(begin, end);
    },
    //上一页
    prevPage() {
      if (this.currentPage == 1) return;

      this.currentPage--;
      this.setCurrentPageData();
    },
    // 下一页
    nextPage() {
      if (this.currentPage == this.totalPage) return;

      this.currentPage++;
      this.setCurrentPageData();
    },
    clearStationcity() {
      var _this = this;

      _this.clearStation.forEach((it) => {
        _this.map.removeLayer(it);
        _this.map.removeSource(it);
      });
      _this.Markers.forEach((it) => {
        it.remove();
      });
      //   _this.$util.clears(_this.map)
    },
    createPulsingDot(color) {
      var size = 200;
      var _this = this;
      return {
        width: size,
        height: size,
        data: new Uint8Array(size * size * 4),

        onAdd: function () {
          var canvas = document.createElement("canvas");
          canvas.width = this.width;
          canvas.height = this.height;
          this.context = canvas.getContext("2d");
        },

        render: function () {
          var duration = 1000;
          var t = (performance.now() % duration) / duration;

          var radius = (size / 2) * 0.3;
          var outerRadius = (size / 2) * 0.7 * t + radius;
          var context = this.context;

          context.clearRect(0, 0, this.width, this.height);

          // 画圆
          context.beginPath();
          context.arc(
            this.width / 2,
            this.height / 2,
            outerRadius,
            0,
            Math.PI * 2
          );
          context.fillStyle = `rgba(${color}, ${1 - t})`;
          context.fill();

          // 画线
          context.beginPath();
          context.arc(this.width / 2, this.height / 2, radius, 0, Math.PI * 2);
          context.fillStyle = `rgba(${color}, 1)`;
          context.strokeStyle = `rgba(${color}, 1)`;
          context.lineWidth = 2 + 4 * (1 - t);
          context.fill();
          context.stroke();

          this.data = context.getImageData(0, 0, this.width, this.height).data;
          _this.map.triggerRepaint();

          return true;
        },
      };
    },
    //国家站点
    guojiazhandian() {
      var _this = this;
      _this.guojiatrue = !_this.guojiatrue;

      var pulsingDot = _this.createPulsingDot("0, 252, 255");
      var pulsingDotred = _this.createPulsingDot("231, 64, 51");

      _this.map.addImage("pulsing-dot1", pulsingDot, { pixelRatio: 8 });
      _this.map.addImage("pulsing-dot2", pulsingDotred, { pixelRatio: 8 });

      _this.clearStation = [];

      if (_this.guojialist == undefined) {
        return;
      }
      for (let i = 0; i < _this.guojialist.length; i++) {
        //画图片点，需要先加载图片 图片路径在页面部署在服务上时可以用相对路径
        _this.clearStation.push(`gjz-${i}`);

        _this.map.addLayer({
          id: `gjz-${i}`,
          type: "symbol",
          source: {
            type: "geojson",
            data: {
              type: "FeatureCollection",
              features: [],
            },
          },
          layout: {
            "icon-image": `pulsing-dot1`,
            "icon-size": 1,
            // "icon-anchor":"bottom",
            //"icon-offset":[0,0],
            "icon-ignore-placement": true,
            "text-ignore-placement": false,
            "text-field": "{name}",
            "text-size": 12,
            "text-anchor": "top",
            "text-allow-overlap": false,
            "icon-anchor": "bottom",
            "text-offset": [0, 0],
            "text-max-width": 8,
            "text-font": ["Microsoft YaHei Regular"],
          },
          paint: {
            "text-color": "#555252",
            "text-halo-color": "#FFFFFF",
            "text-halo-width": 1.33333,
          },
        });

        _this.map.getSource(`gjz-${i}`).setData({
          type: "FeatureCollection",
          features: [
            {
              type: "Feature",
              geometry: {
                type: "Point",
                coordinates: [_this.guojialist[i].lon, _this.guojialist[i].lat],
              },
              properties: {
                name: `${_this.guojialist[i].name}`,
              },
            },
          ],
        });
        var el = document.createElement("div");
        el.className = "marker";

        el.style.width = "15px";
        el.style.height = "15px";
        el.setAttribute("data-name", JSON.stringify(_this.guojialist[i]));
        el.setAttribute("data-type", JSON.stringify(`gjz-${i}`));
        _this.map.setLayoutProperty(`gjz-0`, "icon-image", "pulsing-dot2");
        var elMarker = new SGMap.Marker({
          element: el,
          anchor: "bottom",
        })
          .setLngLat([_this.guojialist[i].lon, _this.guojialist[i].lat])
          .addTo(_this.map);
        _this.Markers.push(elMarker);

        el.addEventListener("click", function (e) {
          var log1 = JSON.parse(e.target.getAttribute("data-name"));
          var type = JSON.parse(e.target.getAttribute("data-type"));
          // 将特定图层中的'pulsing-dot1'图像更改为'new-pulsing-dot'

          _this.clearStation.forEach((it) => {
            if (it == type) {
              _this.map.setLayoutProperty(type, "icon-image", "pulsing-dot2");
            } else {
              _this.map.setLayoutProperty(it, "icon-image", "pulsing-dot1");
            }
          });

          var time = _this.$util.getTime(this.currentDate, "ymd");
          _this.zhantext = log1.name;
          _this.list = [
            {
              name: log1.name,
            },
          ];
          var params = {
            city: _this.city,
            time: time,
            name: log1.name,
          };

          // _this.list.forEach((it) => {})
          _this.dianFN(params);
        });
      }
    },
    confirmTime(value) {
      this.currentDate = value;

      this.endTime = this.$util.getTime(value, "ymd");

      var time = this.$util.getTime(this.currentDate, "ymd");
      var params = {
        city: this.city,
        time: time,
        name: this.zhantext,
      };

      // _this.list.forEach((it) => {})
      this.dianFN(params);
      this.selectTime = false;
    },
    selectTimeMet(type) {
      this.timeType = type;
      this.selectTime = true;
    },

    confirmEmitAreaMet(value) {
      var _this = this;

      SGMap.plugin("SGMap.GeocodingTask").then(function (res) {
        var geocodingTask = new SGMap.GeocodingTask();

        geocodingTask
          .getLocation({
            address: value,
            region: "山西",
            isEncode: false,
          })
          .then(function (result) {
            _this.location = [result.location[0], result.location[1]];

            _this.showComArea = false;
            _this.city = value;
            _this.arr = [_this.city];

            _this.cnty = value;
            _this.title = _this.cnty;
            _this.map.removeImage("pulsing-dot1");
            _this.map.removeImage("pulsing-dot2");
            _this.clearStationcity();
            _this.$util.clears(_this.map);

            _this.$util.initLayershi(value, _this.map);
            _this.$util.searchshi(value, _this.map);
            //设置中心点
            _this.map.setCenter([result.location[0], result.location[1]]);
            //设置缩放
            _this.map.setZoom(7);
            _this.getlist("load");
            // 地图平移
            // _this.map.panTo([
            //   _this.startAddr.point[0],
            //   _this.startAddr.point[1],
            // ])
            var center = _this.map.getCenter();
            var newCenter = new SGMap.LngLat(center.lng, center.lat - 0.5); // 假设向上移动0.01的纬度
            _this.map.panTo(newCenter);
            var time = _this.$util.getTime(_this.currentDate, "ymd");
            var params = {
              city: _this.city,
              time: time,
              name: _this.stationsName,
            };
            // _this.list.forEach((it) => {})

            _this.dianFN(params);
          });
      });
    },

    clicksPopul() {
      this.showComArea = true;
    },
  },
};
</script>
<style type="text/css" lang="less" scoped>
.historyDataWrap {
  width: 100%;
  height: 100%;
  overflow: hidden;
  .rights {
    color: #fff;
  }
  .listbiao {
    position: absolute;
    bottom: 0;
    width: 100%;
    overflow: auto;
    background: #fff;
    overflow: hidden;
    border-radius: 20px 20px 0px 0px;
    .staDistime {
      position: relative;
      width: 100%;

      padding: 10px;
      color: white;
      text-align: center;
      //  height: 45px;
      margin: 0 auto;
      font-weight: 400;
      color: #101010;
      margin-top: 10px;
      margin-bottom: 10px;

      .suntime {
        // width: 345px;
        position: absolute;
        left: 160px;
        display: flex;
        justify-content: center;
        align-items: center;
        top: 20%;
        transform: translate(-50%, -50%);
        height: 34px;
        background: #f5f5f5;
        border-radius: 17px;
        font-size: 14px;
        padding: 10px;
        font-weight: 400;
        color: #101010;
      }
    }
    .topTitle {
      text-align: left;
      font-size: 13px;
      background: white;
      padding: 10px;
      font-weight: 550;
      overflow: hidden;
    }
    .box {
      overflow-x: scroll;
      width: 100%;
      height: 100%;
      display: flex;

      font-size: 13px;
      flex-wrap: nowrap;
      flex-direction: column;
      padding-bottom: 20px;
      .boxsun {
        width: 100%;
        display: flex;
        padding: 10px;
      }
      .topTitle1sun {
        flex: 0 0 60px;
      }

      .tdList {
        width: 100%;
        margin-top: -8px;
        color: #333;
        padding-left: 10px;
        text-align: left;
        display: flex;

        font-size: 13px;
        .tdListsun {
          flex: 0 0 60px;
          display: flex;
          width: 70px;
          height: 50px;

          justify-content: center;
          align-items: center;
          //   white-space: nowrap; /*超出的空白区域不换行*/
          //   overflow: hidden; /*超出隐藏*/
          //   text-overflow: ellipsis; /*文本超出显示省略号*/
        }
      }
      .tdListsunactive {
        display: flex;
        padding: 3px;
        height: 50px;
        margin-right: 10px;
        width: 70px;
        justify-content: center;
        align-items: center;
        flex: 0 0 60px;
        color: #04bde7;
        // white-space: nowrap; /*超出的空白区域不换行*/
        // overflow: hidden; /*超出隐藏*/
        // text-overflow: ellipsis; /*文本超出显示省略号*/
      }
      .select {
        padding: 3px;
        height: 30px;
        background: #ffffff;
        box-shadow: 0px 0px 15px 0px rgba(191, 191, 191, 0.4);
        border-radius: 10px;
      }
      .selectsun {
        background: #ffffff;
        box-shadow: 0px 0px 15px 0px rgba(191, 191, 191, 0.4);
        border-radius: 10px;
        width: 70px;
        margin-top: 7px;
        height: 100px;
        overflow-y: auto;
      }
      //   .tdList:nth-child(odd) {
      //     // background: #f7f7f7;
      //   }
    }

    /deep/ .van-pagination__item--active {
      height: 25px;
    }
    /deep/ .van-pagination__prev {
      height: 25px;
    }
    /deep/ .van-pagination__page {
      height: 25px;
    }
    /deep/ .van-pagination {
    }
    /deep/ .van-pagination__item {
      height: 25px;
    }
  }
}
.hights {
  height: 245px;
}
/deep/  .van-collapse-item__wrapper{
   padding-top: 10px;
}
/deep/ .van-collapse-item__content {
  padding: 2px !important;
}
</style>
